import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import express from "express";
import { Server } from "http";
import { mcpServer } from "../mcp";
import {
  ConfigurationItem,
  ConfigurationKey,
  setInsConfig,
} from "@ap/util/vscode/setInsConfig";
import { login } from "@ap/user/accountsLogin";
let serverInstance: Server | null = null;
let transport: SSEServerTransport | null = null;
// 创建HTTP服务器
export function createHttpServer() {
  const app = express();

  app.get("/ap-mcp", (req, res) => {
    transport = new SSEServerTransport("/ap-mcp-messages", res);
    mcpServer?.connect(transport);
  });

  app.get("/ap-auth/callback", async (req, res) => {
    const params = req.query;
    if (!params) {
      return;
    }
    const token = params.token;
    const userAgent = params.userAgent;

    await setInsConfig(
      ConfigurationItem.USER_CENTER_TOOL,
      ConfigurationKey.ACCOUNT_TOKEN,
      token,
    );
    await setInsConfig(
      ConfigurationItem.USER_CENTER_TOOL,
      ConfigurationKey.USER_AGNET,
      userAgent,
    );
    login();
    const nickname = params.nickname;
    const userId = params.userId;
    res.send(`<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录成功</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f0f2f5;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .success-container {
            background-color: #fff;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            max-width: 400px;
            width: 100%;
        }
        .success-icon {
            color: #52c41a;
            font-size: 72px;
            margin-bottom: 20px;
        }
        .success-title {
            font-size: 24px;
            color: #333;
            margin-bottom: 16px;
        }
        .return-button {
            background-color: #1890ff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            margin-top: 20px;
            transition: background-color 0.3s;
        }
        .return-button:hover {
            background-color: #40a9ff;
        }
    </style>
</head>
<body>
    <div class="success-container">
        <div class="success-icon">✓</div>
        <h1 class="success-title">你好，${nickname}(${userId})</h1>
        <p>ArenaPro插件授权成功</p>
        <button class="return-button" onclick="returnToVSCode()">返回VSCode</button>
    </div>

    <script>
        function returnToVSCode() {
            window.location.href = "vscode://"; 
        }
    </script>
</body>
</html>`);
  });

  app.post("/ap-mcp-messages", (req, res) => {
    if (transport) {
      transport.handlePostMessage(req, res);
    }
  });

  serverInstance = app.listen(25315, (error) => {
    if (error) {
      console.error(`启动ArenaPro服务器失败: ${(error as Error).message}`);
    }
  });
  return app;
}

// 关闭服务器
export function stopHttpServer() {
  if (serverInstance) {
    serverInstance.close(() => {
      console.log("ArenaPro服务器已停止");
    });
    serverInstance = null;
  }
}
